/*   **********************************************************************  **
 **   Copyright notice                                                       **
 **                                                                          **
 **   (c) 2009, Around(J2)ME				                                 **
 **   All rights reserved.                                                   **
 **                                                                          **
 **   This program and the accompanying materials are made available under   **
 **   the terms of the New BSD License which accompanies this    			 **
 **   distribution.											                 **
 **   A copy is found in the textfile LICENSE.txt							 **
 **                                                                          **
 **   This copyright notice MUST APPEAR in all copies of the file!           **
 **                                                                          **
 **   Main developers:                                                       **
 **     Juri Strumpflohner		http://blog.js-development.com	             **
 **		Matthias Braunhofer		http://matthias.jimdo.com                    **
 **                                                                          **
 **  **********************************************************************  */

package com.aroundj2me.model;

import java.util.Calendar;
import java.util.Date;
/**
 * Does the necessary conversion between dates
 *
 */
public class DateUtility {

	/**
	 * Converts a String to a Date object
	 * @param date string representing a date of the form "dd.mm.yyyy"
	 * @return Date
	 */
	public static Date convertStringToDate(String date){
		//date format: dd.mm.yyyy
		Calendar cal = Calendar.getInstance();
		String[] splittedDate = split(date, '.');
		cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(splittedDate[0]));
		int month = Integer.parseInt(splittedDate[1]);
		cal.set(Calendar.MONTH, month-1); //don't know why subtract 1...otherwise date is not correct
		cal.set(Calendar.YEAR, Integer.parseInt(splittedDate[2]));
		return cal.getTime();
	}

	/**
	 * Does the parsing of the date-string which is of the form
	 * dd.mm.yyyy
	 * @param string date string of the form "dd.mm.yyyy"
	 * @param delimiter
	 * @return
	 */
	private static String[] split(String string, char delimiter){
		String[] dateSplit = new String[3];
		int arrayIdx = 0;
		int index = 0;
		for(int i=0; i<string.length(); i++){
			if(string.charAt(i) == delimiter || i==string.length()-1){
				if(i==string.length()-1)
					dateSplit[arrayIdx] = string.substring(index,i+1);
				else
					dateSplit[arrayIdx] = string.substring(index,i);
				index=i+1;
				arrayIdx++;
			}
		}
		return dateSplit;
	}

}
